package com.airena.service.impl;

import com.airena.context.BaseContext;
import com.airena.entity.dto.MessageListDTO;
import com.airena.entity.po.ChatMessage;
import com.airena.entity.po.RoleInfo;
import com.airena.entity.vo.RoleInfoVo;
import com.airena.mapper.ChatMessageMapper;
import com.airena.result.Result;
import com.airena.service.IChatMessageService;
import com.airena.service.IRoleInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 会话消息表 服务实现类
 * </p>
 *
 * @author mender
 * @since 2025-09-28
 */
@Slf4j
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements IChatMessageService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private IRoleInfoService roleInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 聊天记录持久化到mysql
     * @param memoryId
     * @param ChatMessage
     */
    @Override
    public void saveMessages(String memoryId, String ChatMessage) {
        // 从ThreadLocal获取用户ID和角色ID（用于向后兼容）
        Long currentId = BaseContext.getCurrentId();
        Long currentRoleId = BaseContext.getCurrentRoleId();
        saveMessages(memoryId, ChatMessage, currentId, currentRoleId);
    }

    /**
     * 聊天记录持久化到mysql - 重载方法，显式传递用户ID和角色ID
     * @param memoryId
     * @param ChatMessage
     * @param userId
     * @param roleId
     */
    @Override
    public void saveMessages(String memoryId, String ChatMessage, Long userId, Long roleId) {
        ChatMessage chatMessage = new ChatMessage();
        
        // 使用userId参数而不是BaseContext.getCurrentId()
        if (userId != null) {
            chatMessage.setUserId(Math.toIntExact(userId));
        } else {
            // 记录错误并抛出异常，因为用户ID是必须的
            log.error("无法获取当前用户ID，传入的userId为null");
            throw new IllegalStateException("无法获取当前用户ID");
        }
        
        chatMessage.setMemoryId(memoryId);
        
        // 使用roleId参数而不是BaseContext.getCurrentRoleId()
        if (roleId != null) {
            chatMessage.setRoleId(Math.toIntExact(roleId));
        } else {
            // 记录警告但继续执行，因为角色ID可能不是必须的
            log.warn("无法获取当前角色ID，使用默认值0");
            chatMessage.setRoleId(0);
        }
        
        chatMessage.setContent(ChatMessage);
        chatMessage.setCreateTime(LocalDateTime.now());
        this.save(chatMessage);
    }

    /**
     * 查询当前用户的所有聊天记录列表
     */
    @Override
    public Result<RoleInfoVo> getChatMessage() {
        try {
            Long currentId = BaseContext.getCurrentId();
            log.info("获取聊天记录列表，当前用户ID: {}", currentId);
            
            if (currentId == null) {
                log.error("无法获取当前用户ID");
                return Result.error("无法获取当前用户ID");
            }
            
            ListOperations listOperations = redisTemplate.opsForList();
            MessageListDTO firstList = (MessageListDTO) listOperations.getFirst(currentId);
            log.info("从Redis获取到的聊天记录: {}", firstList);
            
            if (firstList == null) {
                log.warn("用户 {} 没有聊天记录", currentId);
                RoleInfoVo roleInfoVo = new RoleInfoVo();
                roleInfoVo.setRoleInfos(Collections.emptyList());
                roleInfoVo.setMemoryIds(Collections.emptyList());
                return Result.success(roleInfoVo);
            }
            
            // 确保roleId不为null
            if (firstList.getRoleId() == null) {
                log.warn("聊天记录中的角色ID为空");
                RoleInfoVo roleInfoVo = new RoleInfoVo();
                roleInfoVo.setRoleInfos(Collections.emptyList());
                roleInfoVo.setMemoryIds(Collections.singletonList(firstList.getMemoryId()));
                return Result.success(roleInfoVo);
            }
            
            log.info("查询角色信息，角色ID: {}", firstList.getRoleId());
            LambdaQueryWrapper<RoleInfo> eq = new QueryWrapper<RoleInfo>().lambda()
                    .eq(RoleInfo::getRoleId, firstList.getRoleId()); // 使用eq而不是in，因为我们只有一个roleId
            List<RoleInfo> list = roleInfoService.list(eq);
            log.info("查询到的角色信息列表: {}", list);

            RoleInfoVo roleInfoVo = new RoleInfoVo();
            roleInfoVo.setRoleInfos(list);
            roleInfoVo.setMemoryIds(Collections.singletonList(firstList.getMemoryId()));
            
            log.info("返回的聊天记录数据: {}", roleInfoVo);

            return Result.success(roleInfoVo);
        } catch (Exception e) {
            log.error("获取聊天记录列表时发生错误: ", e);
            return Result.error("获取聊天记录失败: " + e.getMessage());
        }
    }

    /**
     * 根据memoryId查询详细聊天记录
     * @param memoryId
     * @return
     */
    @Override
    public Result<ChatMessage> getChatMessageList(String memoryId) {
        log.info("根据memoryId查询详细聊天记录: {}", memoryId);
        try {
            ChatMessage chatMessage = chatMessageMapper.selectById(memoryId);
            log.info("查询到的聊天记录: {}", chatMessage);
            return Result.success(chatMessage);
        } catch (Exception e) {
            log.error("根据memoryId查询详细聊天记录时发生错误: ", e);
            return Result.error("查询聊天记录失败: " + e.getMessage());
        }
    }
}